import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Comment } from './entities/comment.entity';
import { CreateCommentDto } from './dto/create-comment.dto';
import { DiscussionPost } from './entities/discussion-post.entity';

@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(Comment)
    private commentRepository: Repository<Comment>,
    @InjectRepository(DiscussionPost)
    private postRepository: Repository<DiscussionPost>,
  ) {}

  async create(createCommentDto: CreateCommentDto): Promise<Comment> {
    // First, check if the post exists
    const post = await this.postRepository.findOne({ 
      where: { id: createCommentDto.postId } 
    });
    
    if (!post) {
      throw new NotFoundException(`Post with ID ${createCommentDto.postId} not found`);
    }

    // Create and save the comment
    const comment = this.commentRepository.create(createCommentDto);
    const savedComment = await this.commentRepository.save(comment);

    // Update the post's comment count
    await this.postRepository.update(
      { id: createCommentDto.postId },
      { commentCount: () => 'comment_count + 1' }
    );

    return savedComment;
  }

  async findByPost(postId: string, page: number = 1, limit: number = 50): Promise<Comment[]> {
    const skip = (page - 1) * limit;
    
    const comments = await this.commentRepository.find({
      where: { postId },
      order: { createdAt: 'DESC' },
      skip,
      take: limit,
    });
    
    // 确保返回的评论作者字段名一致性
    return comments.map(comment => {
      // 确保作者字段的兼容性
      if (comment.author) {
        // 提供username作为name的别名，以兼容前端
        if (comment.author.name && !('username' in comment.author)) {
          // 使用索引签名访问，而不是直接访问不存在的属性
          (comment.author as any)['username'] = comment.author.name;
        }
        
        // 提供avatar作为avatarUrl的别名，以兼容前端
        if (comment.author.avatarUrl && !('avatar' in comment.author)) {
          (comment.author as any)['avatar'] = comment.author.avatarUrl;
        }
      }
      
      return comment;
    });
  }

  async findOne(id: string): Promise<Comment> {
    const comment = await this.commentRepository.findOne({ where: { id } });
    if (!comment) {
      throw new NotFoundException(`Comment with ID ${id} not found`);
    }
    return comment;
  }

  async remove(id: string): Promise<void> {
    // First get the comment to know which post to update
    const comment = await this.findOne(id);
    
    // Delete the comment
    await this.commentRepository.delete(id);
    
    // Update the post's comment count
    await this.postRepository.update(
      { id: comment.postId },
      { commentCount: () => 'comment_count - 1' }
    );
  }
} 